<template>
    <s-layout title="订单列表">
        <view class="search-container">
            <view class="search-box">
                <uni-icons type="search" size="18" color="#999" />
                <input v-model="state.searchKeyword" placeholder="输入订单编号或产品名称" class="search-input"
                       @input="onSearch" @confirm="onSearch" />
                <view v-if="state.searchKeyword" class="clear-btn" @click="clearInterval">
                    <uni-icons type="clear" size="16" color="#999" />
                </view>
            </view>
        </view>

        <su-sticky bgColor="#fff">
            <su-tabs
                :list="tabMaps"
                :scrollable="false"
                @change="onTabsChange"
                :current="state.currentTab"
            />
        </su-sticky>

        <s-empty v-if="state.pagination.total === 0" icon="/static/order-empty.png" text="暂无订单" />

        <view v-else class="order-list-container">
            <view
                class="bg-white order-list-card-box ss-r-10 ss-m-t-14 ss-m-20"
                v-for="order in state.pagination.list"
                :key="order.id"
                @tap="onOrderDetail(order.id)"
            >
                <view class="order-card-header ss-flex ss-col-center ss-row-between ss-p-x-20">
                    <view class="order-no">订单编号：{{ order.orderCode }}</view>
                    <view class="order-state ss-font-26" :class="formatOrderStatusColor(order.orderStatus)">
                        {{ formatOrderStatus(order.orderStatus) }}
                    </view>
                </view>

                <!-- 产品信息 -->
                <view class="border-bottom" v-if="order.cellProductId"> <!-- 假设有产品信息才显示 -->
                    <view class="product-info">
                        <view class="product-name">产品名称：{{ order.productName }}</view> <!-- 需转换成名称 -->
                        <view class="product-name">产品规格：{{ order.cellSpecification }}{{order.isSplit?'拆分':'不拆分'}}X{{order.bagCount}}</view>
                        <view class="product-name">总数量：{{order.totalCells}}X{{order.reservationQuantity}} </view>
                        <view class="product-name">细胞来源：{{order.cellOrigin=='ALLOGENEIC'?'不指定':'自体'}}</view>
                        <view class="product-name" v-if="order.orderStatus=='REJECTED'" style="color: red">驳回原因：{{order.rejectReason}}</view>
                        <view class="product-specs">使用时间：{{ formatDate(order.usageTime) }}</view>
                        <view class="product-specs">创建时间：{{ formatDate(order.createTime) }}</view>
                    </view>
                </view>

                <view class="order-card-footer ss-flex ss-col-center ss-p-x-20 ss-row-right">
                    <view class="ss-flex ss-col-center">
                        <button
                            class="tool-btn ss-reset-button"
                            @tap.stop="onOrderDetail(order.id)"
                        >
                            查看详情
                        </button>
                        <button
                            class="tool-btn ss-reset-button ui-BG-Main-Gradient"
                            v-if="order.orderStatus=='REJECTED'"
                            @tap.stop="goToEdit(order.id)"
                        >
                            编辑
                        </button>
                        <!-- 根据实际业务需求添加更多操作按钮 -->
                    </view>
                </view>
            </view>

            <!-- 底部占位空间，防止最后一个订单被悬浮按钮遮挡 -->
            <view class="bottom-placeholder"></view>
        </view>

        <uni-load-more
            v-if="state.pagination.total > 0"
            :status="state.loadStatus"
            :content-text="{ contentdown: '上拉加载更多' }"
            @tap="loadMore"
            class="load-more-margin"
        />

        <!-- 悬浮在底部的新增订单按钮 -->
        <view class="fixed-bottom-bar">
            <view class="floating-add-container">
                <button class="ss-reset-button floating-add-btn ui-BG-Main-Gradient" @tap="goToAddOrder">
                    <uni-icons type="plus" size="20" color="#fff" />
                    <text class="add-btn-text">新增订单</text>
                </button>
            </view>
        </view>

    </s-layout>
</template>

<script setup>
import { reactive } from 'vue';
import { onLoad,onShow, onReachBottom, onPullDownRefresh } from '@dcloudio/uni-app';
import sheep from '@/sheep';
import _ from 'lodash-es';
import { formatDate, resetPagination } from '@/sheep/helper/utils';
import ReservationRecordApi from '@/sheep/api/system/reservationRecord';

// 订单状态枚举
const ORDER_STATUS = {
    PENDING_REVIEW: '待审核',
    PENDING_PROD: '待生产',
    PRODUCING: '生产中',
    PRODUCED: '待提货',
    PICKED_UP: '已完成',
    REJECTED: '已驳回'
};

const state = reactive({
    currentTab: 0,
    searchKeyword: '',
    pagination: {
        list: [],
        total: 0,
        pageNo: 1,
        pageSize: 10,
    },
    loadStatus: 'more',
});

const tabMaps = [
    { name: '全部', value: null },
    { name: '待审核', value: 'PENDING_REVIEW' },
    { name: '待生产', value: 'PENDING_PROD' },
    { name: '生产中', value: 'PRODUCING' },
    { name: '待提货', value: 'PRODUCED' },
    { name: '已完成', value: 'PICKED_UP' },
    { name: '已驳回', value: 'REJECTED' },
];

// 格式化订单状态文字
const formatOrderStatus = (status) => {
    return ORDER_STATUS[status] || '未知状态';
};

// 格式化订单状态颜色
const formatOrderStatusColor = (status) => {
    const colorMap = {
        PENDING_REVIEW: 'warning-color',
        PENDING_PROD: 'warning-color',
        PRODUCING: 'primary-color', // 假设有主要颜色
        PRODUCED: 'success-color',
        PICKED_UP: 'success-color',
        REJECTED: 'danger-color'
    };
    return colorMap[status] || 'info-color';
};

const onSearch = () => {
    resetPagination(state.pagination);
    getOrderList();
};

const onTabsChange = (e) => {
    if (state.currentTab === e.index) return;
    state.currentTab = e.index;
    resetPagination(state.pagination);
    getOrderList();
};

const onOrderDetail = (id) => {
    sheep.$router.go('/pages/order/cellOrder/detail', { id });
};

const goToAddOrder = () => {
    sheep.$router.go('/pages/order/cellOrder/add'); // 假设新增页面路由
};

const goToEdit = (id) => {
    sheep.$router.go('/pages/order/cellOrder/edit', { id }); // 假设编辑页面路由
};
const clearInterval = ()=>{
    state.searchKeyword = ''
    onSearch()
}


async function getOrderList() {
    state.loadStatus = 'loading';
    const params = {
        pageNo: state.pagination.pageNo,
        pageSize: state.pagination.pageSize,
        orderStatus: tabMaps[state.currentTab].value,
    };
    if (state.searchKeyword) {
        // 根据后端接口要求，可能需要指定搜索字段，例如 orderCode or productName
        params.keyword = state.searchKeyword;
    }

    try {
        const { code, data } = await ReservationRecordApi.getPage(params); // 假设的API方法
        if (code !== 0) return;

        state.pagination.list = _.concat(state.pagination.list, data.list);
        state.pagination.total = data.total;
        state.loadStatus = state.pagination.list.length < data.total ? 'more' : 'noMore';
    } catch (error) {
        console.error('获取订单列表失败:', error);
        state.loadStatus = 'noMore';
    }
}
// 添加一个专门的刷新方法
const refreshList = async () => {
    console.log('手动触发刷新列表');
    resetPagination(state.pagination);
    await getOrderList();
};
const loadMore = () => {
    if (state.loadStatus !== 'more') return;
    state.pagination.pageNo++;
    getOrderList();
};

onLoad(async (options) => {
    const tabIndex = tabMaps.findIndex(tab => tab.value === options.type);
    if (tabIndex !== -1) {
        state.currentTab = tabIndex;
    }
    // await getOrderList();
});
onShow(() => {
    // 每次页面显示时刷新
    console.log('onShow: 页面显示，刷新订单列表');
    refreshList();
});


onReachBottom(() => {
    loadMore();
});

onPullDownRefresh(async () => {
    resetPagination(state.pagination);
    await getOrderList();
    uni.stopPullDownRefresh();
});

</script>

<style lang="scss" scoped>
.search-container {
    padding: 20rpx;
    background: #fff;
    border-bottom: 2rpx solid #f0f0f0;
}

.search-box {
    display: flex;
    align-items: center;
    background: #f8f9fa;
    border-radius: 50rpx;
    padding: 20rpx 30rpx;
    gap: 20rpx;
}

.search-input {
    flex: 1;
    font-size: 28rpx;
    color: #333;

    &::placeholder {
        color: #999;
    }
}

.clear-btn {
    padding: 10rpx;

    &:active {
        opacity: 0.6;
    }
}

.order-list-container {
    position: relative;
    //min-height: 100vh;
}

.order-list-card-box {
    .order-card-header {
        height: 80rpx;
        .order-no {
            font-size: 28rpx;
            font-weight: 500;
        }
        .order-state {
            font-weight: 500;
        }
    }

    .product-info {
        padding: 20rpx;
        .product-name {
            font-size: 26rpx;
            color: #333;
            margin-bottom: 10rpx;
        }
        .product-specs {
            font-size: 24rpx;
            color: #999;
        }
    }

    .order-card-footer {
        height: 100rpx;
        .tool-btn {
            width: 160rpx;
            height: 60rpx;
            background: #f6f6f6;
            font-size: 26rpx;
            border-radius: 30rpx;
            margin-left: 20rpx;
        }
    }
}

/* 底部占位空间，防止最后一个订单被悬浮按钮遮挡 */
.bottom-placeholder {
    height: 80rpx;
}

/* 悬浮在底部的新增订单按钮样式 */
.fixed-bottom-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 999;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(10rpx);
    border-top: 1rpx solid rgba(0, 0, 0, 0.1);
    padding: 20rpx;
    box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.floating-add-container {
    display: flex;
    justify-content: center;
    align-items: center;
}

.floating-add-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10rpx;
    width: 100%;
    height: 80rpx;
    border-radius: 40rpx;
    font-size: 30rpx;
    color: #fff;
    box-shadow: 0 8rpx 24rpx rgba(0, 122, 255, 0.3);
    transition: all 0.3s ease;

    &:active {
        transform: scale(0.95);
        box-shadow: 0 4rpx 12rpx rgba(0, 122, 255, 0.2);
    }
}

.add-btn-text {
    font-weight: 500;
}

.warning-color { color: #faad14; }
.danger-color { color: #ff3000; }
.success-color { color: #52c41a; }
.info-color { color: #999999; }
.primary-color { color: #007aff; } // 示例主要颜色
</style>

